package com.example.myapplication;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.Dao.CommentDao;
import com.EventHandler.ArticleLoader;
import com.EventHandler.CommentManager;
import com.EventHandler.EventHandler;
import com.adapter.CommentAdapter;
import com.news.model.Comment;

import java.util.List;


/**
 * Activity 显示新闻详情及相关操作。
 */
public class ArticleActivity extends AppCompatActivity {
    private ArticleLoader articleLoader;
    private CommentManager commentManager;
    private EventHandler eventHandler;
    private CommentDao commentDao;
    private RecyclerView commentsRecyclerView;
    private CommentAdapter commentsAdapter;
    private List<Comment> commentList;
    private int newsId;
    private int userId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_details);
        // 从Intent中获取新闻ID和用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("user_info",MODE_PRIVATE);
        newsId = getIntent().getIntExtra("newsId", -1);
        userId = sharedPreferences.getInt("userid",-1);
        String username = sharedPreferences.getString("username",null);
        //创建对象
        articleLoader = new ArticleLoader(this, newsId);
        commentManager = new CommentManager(this, newsId, userId);
        eventHandler = new EventHandler(this, userId, newsId, username,commentManager);
        //初始化UI组件
        articleLoader.initializeUI();
        commentManager.initializeUI();
        eventHandler.setListeners();
        // 加载数据
        commentDao = new CommentDao(this);
        commentList = commentDao.getCommentsByNewsId(newsId);
        // 初始化RecyclerView
        commentsRecyclerView = findViewById(R.id.comments_view);
        commentsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 创建并设置适配器
        commentsAdapter = new CommentAdapter(this, commentList);
        commentsRecyclerView.setAdapter(commentsAdapter);
        for(Comment c:commentList){
            Log.i("评论",c.toString());
        }
        articleLoader.loadData();
        eventHandler.loadStatus();
    }
    public void addCommentAndRefresh(String commentContent) {
        long currentTime = System.currentTimeMillis(); // 当前时间戳
        commentManager.addComment(userId, commentContent, currentTime);
        commentList.clear(); // 清空旧的评论列表
        commentList.addAll(commentDao.getCommentsByNewsId(newsId)); // 加载最新的评论
        commentsAdapter.notifyDataSetChanged(); // 更新RecyclerView显示最新评论
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        articleLoader.close();
        commentManager.close();
        eventHandler.close();
    }
}
